package io.renren.config;

import io.renren.common.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/25
 * Time: 9:29
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Slf4j
@Component
@Configuration
@EnableAutoConfiguration
public class RedisConfig extends CachingConfigurerSupport {


    @Value("${spring.redis.host}")
    private String host;  // Redis服务器地址
    @Value("${spring.redis.port}")
    private int port;  // Redis服务器连接端口
    @Value("${spring.redis.password}")
    private String password;  // Redis服务器连接密码（默认为空）
    @Value("${spring.redis.pool.timeout}")
    private int timeout;  // 连接超时时间（毫秒）
    @Value("${spring.redis.database}")
    private int database;  // 连接超时时间（毫秒）
    @Value("${spring.redis.pool.max-active}")
    private int maxTotal;  // 连接池最大连接数（使用负值表示没有限制）
    @Value("${spring.redis.pool.max-wait}")
    private int maxWaitMillis;  // 连接池最大阻塞等待时间（使用负值表示没有限制）
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;  // 连接池中的最大空闲连接
    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;  // 连接池中的最小空闲连接



    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(true);
        config.setTestWhileIdle(true);
        config.setNumTestsPerEvictionRun(2);
        config.setTimeBetweenEvictionRunsMillis(30000);
        config.setMinEvictableIdleTimeMillis(60000);
        config.setSoftMinEvictableIdleTimeMillis(60000);
        return config;
    }


    /**
     * 配置JedisPoolConfig
     * @return JedisPoolConfig实体
     */
    /*@Bean(name = "jedisPoolConfig")
    public JedisPoolConfig jedisPoolConfig() {


        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(this.maxTotal);  //  连接池最大连接数（使用负值表示没有限制）
        jedisPoolConfig.setMaxWaitMillis(this.maxWaitMillis);  // 连接池最大阻塞等待时间（使用负值表示没有限制）
        jedisPoolConfig.setMaxIdle(this.maxIdle);  // 连接池中的最大空闲连接
        jedisPoolConfig.setMinIdle(this.minIdle);  // 连接池中的最小空闲连接
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnCreate(true);
        jedisPoolConfig.setTestWhileIdle(true);
        return jedisPoolConfig;
    }*/


    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig());
        redisConnectionFactory.setDatabase(database);
        redisConnectionFactory.setHostName(host);
        redisConnectionFactory.setPort(port);
        redisConnectionFactory.setPassword(password);
        redisConnectionFactory.setTimeout(timeout);
        redisConnectionFactory.setUsePool(true);
        return redisConnectionFactory;
    }

    @Bean
    public <K, V> RedisTemplate<K, V> redisTemplate() {
        RedisTemplate<K, V> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setEnableTransactionSupport(true);
        template.afterPropertiesSet();
        return template;
    }





    @Bean(name = "jedisPool")
    public JedisPool getJedisPool(){

        JedisPoolConfig config = jedisPoolConfig();
        JedisPool pool = new JedisPool(config,host,port,timeout,password);
        return pool;
    }


    /**
     * 实例化 RedisConnectionFactory 对象
     * @param poolConfig
     * @return
     */
  /*  @Bean(name = "jedisConnectionFactory")
    public RedisConnectionFactory jedisConnectionFactory(@Qualifier(value = "jedisPoolConfig") JedisPoolConfig poolConfig) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
        jedisConnectionFactory.setHostName(this.host);
        jedisConnectionFactory.setPort(this.port);
        jedisConnectionFactory.setDatabase(this.database);
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }*/

    /**
     *  实例化 RedisTemplate 对象
     * @return
     */
    /*@Bean(name = "redisTemplate")
    public RedisTemplate<String, String> functionDomainRedisTemplate() {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new EntityRedisSerializer());
        redisTemplate.setValueSerializer(new EntityRedisSerializer());
        redisTemplate.afterPropertiesSet();
        redisTemplate.setEnableTransactionSupport(true);
        return redisTemplate;
    }*/

    /**
     *   @Cacheable 触发缓存入口
     *
         @CacheEvict 触发移除缓存

         @CacahePut 更新缓存

         @Caching 将多种缓存操作分组

         @CacheConfig 类级别的缓存注解，允许共享缓存名称
     *
     */

    @Bean
    public KeyGenerator keyGenerator() {

        return new KeyGenerator() {
            //为给定的方法及其参数生成一个键
            //格式为：com.frog.mvcdemo.controller.FrogTestController-show-[params]
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName());//类名
                sb.append("-");
                sb.append(method.getName());//方法名
                sb.append("-");
                for (Object param: params ) {
                    if(param instanceof String[]){
                        String[] param1 = (String[]) param;
                        sb.append(StringUtils.join(param1,","));
                    }else{
                        sb.append(param.toString());//参数
                    }

                }
                return sb.toString();
            }
        };
    }


    /**
     * 设置RedisCacheManager
     * 使用cache注解管理redis缓存
     *
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        //设置默认的过期时间(以秒为单位)
        redisCacheManager.setDefaultExpiration(Constant.getRedisKeyExpireTimeDayToSecond(1));
       // redisCacheManager.setExpires();设置缓存区域(按key)的过期时间(以秒为单位)
        return redisCacheManager;
    }


}
